package com.zhang.first.day07;

import com.zhang.first.utils.ClickEvent;
import com.zhang.first.utils.ClickEventSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoFlatMapFunction;
import org.apache.flink.util.Collector;

/**
 * @title: 查询流实现
 * @author: zhang
 * @date: 2022/1/20 17:02
 */
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<ClickEvent> clickSource = env.addSource(new ClickEventSource());
        //查询流
        DataStreamSource<String> queryStream = env.socketTextStream("localhost", 9999);

        clickSource.keyBy(r -> r.name)
                .connect(queryStream.setParallelism(1).broadcast())
                .flatMap(new CoFlatMapFunction<ClickEvent, String, ClickEvent>() {
                    private String query = "";

                    @Override
                    public void flatMap1(ClickEvent value, Collector<ClickEvent> out) throws Exception {
                        if (value.name.equals(query)) out.collect(value);
                    }

                    @Override
                    public void flatMap2(String value, Collector<ClickEvent> out) throws Exception {
                        query = value;
                    }
                })
                .print();

        env.execute();
    }
}
